/**
 * Created by yijx on 2017/3/21.
 */

//选中一行备料计划
var selectReqPickm = null;
$(function () {
    var matconfirm = $('#matconfirm'),
        rtnmat = $('#rtnmat'),
        sqtrans = $('#savetransbill');
    //领料确认
    matconfirm.on('click', function () {
        //confirmMat();
    	comfirmTrans();
    });

    //要料完成
    rtnmat.on('click', function () {
        reqPickmDone();
    });
    
    //申请转库
    sqtrans.on('click', function () {
    	getWeight();
    });

});

//点击申请转库按钮
function getWeight() {
    //修改弹框遮罩标题
    $(".theme-popover h4.text-center")[0].innerText = "申请转库";
    //修改弹框遮罩内容
    var form = $(".theme-popbod.dform");
    form.empty();
    var result = "";
    result += "<div class='input-group'>" +
        "<input id='tranweightNum' class='form-control' type='number' placeholder='转库重量' />" +
        "<span class='input-group-btn'>" +
        "<button type='button' class='btn' onclick='sqTransbill()'>生产转库单</button></span></div> ";

    form.append(result);
    //弹出遮罩
    $("#maskin").click();
    $(".form-control").focus();
}

//要料完成，手工完工备料计划
function reqPickmDone() {
    if (null == selectReqPickm) {
        alert("请选择一行备料申请啊！")
    } else {
        var selectRow = $("#req").find("tbody")[0].children[selectReqPickm];
        var reqNum = selectRow.children[6].innerText;
        var doneNum = selectRow.children[8].innerText;
        var result = confirm("该行备料申请要料" + reqNum + "，已转库" + doneNum + "，确认完成？");
        if (result) {
            var billidNode = selectRow.children[0].firstChild;
            var billid = billidNode.innerText;
            var rowno = billidNode.nextSibling.innerText;
            var bill = {
                billid:billid,
                rowno:rowno
            }
            doneReqPickm(selectReqPickm,bill);
        }
    }
}

//后台处理要料完成成功后前台操作
function reqPickmDoneOpr(msg,selectRowNo) {
    var flag = msg.flag;
    if (flag == 0) {
        alert("后台处理错误，请稍后重试！")
    }else{
    	alert("备料申请完成！");
        var selectRow = $("#req").find("tbody")[0].children[selectRowNo];
        selectRow.children[0].lastChild.outerHTML = "";
        selectRow.lastChild.innerText = "完成";
        selectReqPickm = null;
    }
}



function rowAddClick() {
    newReqPickm(dataInputLable, dataLable);
}


//自制备料申请
function newReqPickm(dataInputLable, dataLable) {
    if(selectedTask.length>0){
        alert("保存备料申请后才能自制新增！")
        return;
    }

    //修改弹框遮罩标题
    $(".theme-popover h4.text-center")[0].innerText = "新增备料申请";
    //修改弹框遮罩内容
    var form = $(".theme-popbod.dform");
    form.empty();
    var result = "<ul class='list-group'>";

    //弹出后只能编辑物料编码
    result += "<li class='list-group-item'>"+
        "<div class='input-group " + dataInputLable[0] +
        "'><input class='form-control' placeholder='输入" +
        dataInputLable[1] + "' type='text'>" +
        "<span class='input-group-btn'><button class='btn btn-small btn-default' type='button' " +
        "onclick='searchMat()'><i class='glyphicon glyphicon-search'></i></button></span></li>";
    //其它字段
    result += "<li class='list-group-item pkL' style='display: none;'><input type='text' ></li>";
    for (var x in dataLable) {
        result += "<li class='list-group-item " + x + "' ><div class='input-group " + x +"'>"+
            "<span class='input-group-addon'>"+dataLable[x]+":</span>"+
            "<input class='form-control' type='text' readonly='true'></div></li>";
    }
    result += "<button class='btn btn-success' type='button' onclick='saveEditReqPickm()'>确定</button>"
    result += "<button class='btn btn-success' type='button' onclick='cleanMaterial()'>重置</button>"
    result += "</ul>";

    form.append(result);
    //弹出遮罩
    $("#maskin").click();
    $("."+dataInputLable[0]+" input").focus();
}

var dataInputLable = [
    "matCodeL",
    "物料编码"
]
//自制备料申请需要显示的字段
var dataLable = {
    matnameL: "物料名称",
    matspecL: "物料规格",
    mattypeL: "物料型号",
    matBatchL: "物料批次",
    reqNumL: "需求重量",
    matunitL: "物料单位",
    reqTimeL: "送达时限"
}


//向NC查询物料编码，获得物料详细信息填充到界面上
function searchMat() {
    var matCode = $("." + dataInputLable[0]+" input")[0].value;
    if (null == matCode || matCode.length == 0) {
        alert("物料编码不能为空!")
        return;
    }

    //根据物料编码后台查询物料详细信息
    searchMatFromServer(matCode);

}

//物料编码后台查询物料详细信息后处理
function searchMatHandler(msg) {
    if(msg.pk == null){
        alert("没有查询到物料信息！");
        return;
    }
    //物料编码不可编辑
    $("."+dataInputLable[0])[0].readOnly=true;

    //填充物料信息
    for(var x in msg){
        $("."+x+"L input")[0].value = msg[x];
    }
    //需求重量、送达时限可编辑
    editable();
}

//需求重量、送达时限可编辑
function editable() {
    $(".list-group-item.reqNumL input")[0].readOnly = false;
    $(".list-group-item.reqNumL input")[0].focus();

    $(".list-group-item.reqTimeL input")[0].readOnly = false;
    $(".list-group-item.reqTimeL input")[0].type = "time";
}

//保存自制备料申请
function saveEditReqPickm() {
    var inputs = $(".list-group-item input");
    var reqNum = inputs[6].value;
    if(isNaN(parseFloat(reqNum)) || reqNum<=0){
        alert("需求重量必须非空且大于0！")
        return;
    }
    var reqTime = inputs[8].value;
    var timeFrag = reqTime.split(":");
    if(0>timeFrag[0] || timeFrag[0]>23 || 0>timeFrag[1] ||
        timeFrag[1]>59 || !isInteger(timeFrag[0]) || !isInteger(timeFrag[1])){
        alert("送达时限不合规范")
        return;
    }
    var reqPickm = {
        billid: "",
        matcode: inputs[1].value,
        matname: inputs[2].value,
        matspec: null == inputs[2].value?"":inputs[3].value,
        mattype: null == inputs[3].value?"":inputs[4].value,
        matbatch: null == inputs[4].value?"":inputs[5].value,
        donenum: 0,
        reqnum: reqNum,
        matunit: inputs[7].value,
        reqtime: reqTime
    }
    var editRowNo = addReqPickm([reqPickm]);
    var reqEditRow = {
        editRowNo:editRowNo,
        matCode :reqPickm.matcode,
        matBatch:reqPickm.matbatch,
        reqNum:reqPickm.reqnum,
        reqTime:reqPickm.reqtime
    }
    editReqpickm.push(reqEditRow);

    adaptTH();
    $('.theme-poptit .close').click();
}

//重置物料信息
function cleanMaterial(){
    //所有信息清空，除物料编码外不可编辑
    var inputs = $(".list-group-item input");
    for(var x=0;x<inputs.length;x++){
        inputs[x].value = null;
    }
    $(".list-group-item.reqNumL input")[0].readOnly = true;
    $(".list-group-item.reqTimeL input")[0].readOnly = true;

    //物料编码可编辑
    $("."+dataInputLable[0])[0].readOnly=false;
    $(".form-control").focus();
}


//备料申请行点击处理
function reqRowClick(row) {
	var col =row.childNodes;
    var checkbox = col[0];
    if(checkbox.children.length <=2){
        return;
    }
    
//	if (selectedTask.length > 0) {
//        return;
//    }
//    var tBody = $("#req").find("tbody");
//    //如果点击行处于完成状态，则点击没有效果
//    if (null == row.childNodes[0].lastChild.checked) {
//        return;
//    }
    var tBody = $("#reqsq").find("tbody");
    tBody.empty();
    if(!checkbox.firstChild.checked){
    	row.childNodes[0].firstChild.checked = true;
        selectReqPickm = row.rowIndex - 1;
        var cpickmid = row.childNodes[0].childNodes[2].innerText;
        //alert(cpickmid);
        getReqPickm(cpickmid);
    }else{
    	row.childNodes[0].firstChild.checked = false;
    	selectReqPickm = null;
    }
//    //只选中点击行
//    if (null == selectReqPickm) {
//        row.childNodes[0].lastChild.checked = true;
//        selectReqPickm = row.rowIndex - 1;
//    } else {
//        tBody[0].children[selectReqPickm].childNodes[0].lastChild.checked = false;
//        if (selectReqPickm == row.rowIndex - 1) {
//            selectReqPickm = null;
//        } else {
//            row.childNodes[0].lastChild.checked = true;
//            selectReqPickm = row.rowIndex - 1;
//        }
//    }
}

//点击领料确认按钮
function confirmMat() {
    //修改弹框遮罩标题
    $(".theme-popover h4.text-center")[0].innerText = "领料确认";
    //修改弹框遮罩内容
    var form = $(".theme-popbod.dform");
    form.empty();
    var result = "";
    result += "<div class='input-group'>" +
        "<input id='tranbillidrowno' class='form-control' type='text' placeholder='转库单号' />" +
        "<span class='input-group-btn'>" +
        "<button type='button' class='btn' onclick='showTransInfo()'>查询</button></span></div> ";

    form.append(result);
    //弹出遮罩
    $("#maskin").click();
    $(".form-control").focus();
}

//显示转库单信息
function showTransInfo() {
	var tranbillid=$("#tranbillidrowno").val();
	var param={
			transBillCode:tranbillid,
			rowno:"10"
	};
	$.ajax({
        type: "post",
        url: "getTransBillInfo",
        data: param,
        dataType: "json",
        timeout: 30000,
        success: function (msg) {
            if(msg&&msg.vbillcode){
            	var form = $(".theme-popbod.dform");
            	form.empty();
                var result = "<ul class='list-group'>";
                result += "<li class='list-group-item'>" + "转库单号: " + msg.vbillcode + "</li>";
                result += "<li class='list-group-item'>" + "转库单行号: " + msg.rowno + "</li>";
                if(msg.matinfo){
                	result += "<li class='list-group-item'>" + "物料名称: " + msg.matinfo.matname + "</li>";
                	result += "<li class='list-group-item'>" + "规格: " + msg.matinfo.matspec + "</li>";
                	result += "<li class='list-group-item'>" + "型号: " + msg.matinfo.mattype + "</li>";
                	result += "<li class='list-group-item'>" + "转库数量: " + msg.nnum + msg.matinfo.dw + "</li>";
                	result +="<div class='form-group'>";
                    result +="<label for='batchcode' class='col-sm-2 control-label'>批次号</label>";
                    result +="<div class='col-sm-10'>";
                    result +="<select id='batchcode' name='batchcode' onclick='batchcodeChange()' type='text' class='form-control'></select>";
                    result +="</div>";
                    result +="</div>";
                    result +="<div class='weight'>";
                    result +="<label for='weight' class='col-sm-2 control-label'>重量</label>";
                    result +="<div class='nnum'>";
                    result +="<input id='weight' name='weight' class = 'weightnnum' type='text' value=''/>";
                    result +="</div>";
                    result +="</div>";
                }
                result += "<button class='btn btn-success' type='button' onclick='transBillOK(\""+msg.vbillcode+"\",\""+msg.rowno+"\")'>完成卸货</button>"
                result += "</ul>";
                form.append(result);
                var batchcode = $("#batchcode").empty();
                batchcode.append("<option value=' '></option>");
                var batchcodeMsg = msg.batchcode;
                for(var id in batchcodeMsg){
                	batchcode.append("<option value='"+batchcodeMsg[id].pk_batchcode+"'>"+batchcodeMsg[id].batchcode+"</option>");
                }
            }
        }
    });
	
}
var pk_batchcode;
var batchcode;
//切换组织后，仓库站点置空,重新获取仓库信息
function batchcodeChange(){
    if($('#batchcode').val()==""){
        alert("必须先选择批次号！");
        return;
    }
    pk_batchcode = $('#batchcode').val();
    batchcode = $('#batchcode').find("option:selected").text();
    
};

//转库单信息标记
var billLabel = {
    billCode: "转库单号",
    rowNo: "行号",
    matName: "物料名称",
    matSpec: "物料规格",
    matType: "物料型号",
    matBatch: "批次号",
    nnum: "装车重量"
}

//解码转库单二维码信息
function decodeTransInfo(transInfo) {
    var values = transInfo.split("//");
    var transBill = {
        billCode: values[0],
        rowNo: values[1],
        matName: values[2],
        matSpec: values[3],
        matType: values[4],
        matBatch: values[5],
        nnum: values[6]
    }
    return transBill;
}

//领料界面点击确定按钮
function  transBillOK(transbillcode,rowno) {
    var result = confirm("即将发空车，请确定车已清空！");
    var weightnum = $('#weight').val();
    if (result) {
        //关闭遮罩
        $('.theme-poptit .close').click();
        //转库单推后台
        var info={
        		transBillCode:transbillcode,
    			rowno:rowno,
    			pk_batchcode:pk_batchcode,
    			batchcode:batchcode,
    			weight:weightnum,
        };
        transConfirm(info);
    }
}

//领料确认后台处理成功
function transConfirmed(msg) {
	//提示确认是否成功
	if(msg.success=="1"){
		alert("确认成功");
	}else if(msg.success=="0"){
		alert("确认失败："+msg.errinfo);
		return;
	}
    //重新刷新机台数据
	taskQuery();
    mask();
    adaptTH();
    /*
    var rows = $("#req tbody tr");
    for(var i=0;i<rows.length;i++){
        if(rows[i].children[0].children[0].innerText==msg.billid && rows[i].children[0].children[1].innerText ==msg.rowNo){
            rows[i].children[7].childNodes[0].nodeValue =parseFloat(rows[i].children[7].childNodes[0].nodeValue)+parseFloat(msg.naccoutnum);
            break;
        }
    }
    */
}